package com.leoncom.sms_silencer.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.leoncom.sms_silencer.MuterReceiver;
import com.leoncom.sms_sliencer.R;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class TaskScheduler {
	
	private static int muteRequestCodeBase = 100;
	private static int unmuteRequestCodeBase = 200;
	private static int JOB_START_NOTIFY_ID = 13487;
	
	public static void destroyAlarm(Context ctxt, SilencerTask curTask) {
		 final AlarmManager alarm = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
		 boolean[] dayOfWeek = curTask.getRepeatedDays();
		 for(int i = 0; i < dayOfWeek.length; i++) {
			 if(dayOfWeek[i] == true) {
				 PendingIntent mutePendingIntent = getBoardCastPendingIntent(ctxt, "tag", "Mute", muteRequestCodeBase + i);
				 PendingIntent unmutePendingIntent = getBoardCastPendingIntent(ctxt, "tag", "UnMute", unmuteRequestCodeBase + i);
				 alarm.cancel(mutePendingIntent);
				 alarm.cancel(unmutePendingIntent);
			 }
		 }
		 SmsLogger.append("alarm canceled");
		 String AppName = ctxt.getResources().getString(R.string.app_name);
		 NotifyManagerHelper.notifyMessage(ctxt, AppName, ctxt.getResources().getString(R.string.TurnOffMuteAlarm), 
				 JOB_START_NOTIFY_ID);
	}
	
	//set mute alarm
	public static void scheduleAlarm(Context ctxt, SilencerTask curTask) {
		 final AlarmManager alarm = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
		 boolean[] dayOfWeek = curTask.getRepeatedDays();
		 Calendar nowCal = Calendar.getInstance();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		 for(int i = 0; i < dayOfWeek.length; i++) {
			 if(dayOfWeek[i] == true) {
				 // mute task
				 Calendar muteCal = getTaskCalendar(i, curTask.getHour(), curTask.getMin(), 0);
				 PendingIntent mutePendingIntent = getBoardCastPendingIntent(ctxt, "tag", "Mute", muteRequestCodeBase + i);
				 
				 // unmute task
				 Calendar unMuteCal = getTaskCalendar(i, curTask.getHour(), curTask.getMin(), curTask.getPeriod());
				 PendingIntent unmutePendingIntent = getBoardCastPendingIntent(ctxt, "tag", "UnMute", unmuteRequestCodeBase + i);
				 
				 // if unmute task should trigger before, delay mute&unmute task to next week
				 if(unMuteCal.before(nowCal)) {
					 Log.i("mute delay", sdf.format(muteCal.getTime()));
					 Log.i("unmute delay", sdf.format(unMuteCal.getTime()));
					 muteCal.add(Calendar.WEEK_OF_YEAR, 1);
					 unMuteCal.add(Calendar.WEEK_OF_YEAR, 1);
				 }
				 
				 alarm.setRepeating(AlarmManager.RTC_WAKEUP, muteCal.getTimeInMillis(),
						 AlarmManager.INTERVAL_DAY * 7, mutePendingIntent);
				 alarm.setRepeating(AlarmManager.RTC_WAKEUP, unMuteCal.getTimeInMillis(),
						 AlarmManager.INTERVAL_DAY * 7, unmutePendingIntent);
				 
				 SmsLogger.append("mute at " + sdf.format(muteCal.getTime()));
				 SmsLogger.append("unmute at " + sdf.format(unMuteCal.getTime()));
			}
		 }
		
		 SmsLogger.append("Service Create, Hour:" + curTask.getHour() + ",Min:" + curTask.getMin()
				 + ",Period:" + curTask.getPeriod() + ", Days:" + curTask.concatDaysIndexToString());
		 String HourName = ctxt.getResources().getString(R.string.ShortHours);
		 String MinName = ctxt.getResources().getString(R.string.ShortMinutes);
		 String LastName = ctxt.getResources().getString(R.string.PeriodLast);
		 String AppName = ctxt.getResources().getString(R.string.app_name);
		 String[] inboxString = new String[3];
		 inboxString[0] = curTask.concatPlainDayString(ctxt);
		 inboxString[1] = curTask.getHour() + HourName + curTask.getMin() + MinName;
		 inboxString[2] = LastName + curTask.getPeriod() + MinName;
		 NotifyManagerHelper.notifyInboxMessage(ctxt, AppName, ctxt.getResources().getString(R.string.TurnOnMuteAlarm), 
				 JOB_START_NOTIFY_ID, inboxString);
	}
	
	private static PendingIntent getBoardCastPendingIntent(Context ctxt, String key, String value, int code) {
		Intent intent = new Intent(ctxt, MuterReceiver.class);
		Bundle bundle = new Bundle();
		bundle.putString(key, value);
		bundle.putInt("code", code);
		intent.putExtras(bundle);
		return PendingIntent.getBroadcast(ctxt, code, intent, 0);
	}
	
	private static Calendar getTaskCalendar(int dayOfWeek, int hour, int min, int delayMinutes) {
		Calendar calNew = Calendar.getInstance();
		
		//DAY_OF_WEEK from 1 to 7, not 0 to 6
		calNew.set(Calendar.DAY_OF_WEEK, dayOfWeek + 1);
		calNew.set(Calendar.HOUR_OF_DAY, hour);
		calNew.set(Calendar.MINUTE, min);
		calNew.add(Calendar.MINUTE, delayMinutes);
		return calNew;
	}
}
